package org.yuci.selenium;

import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;

public class AbstractPageAbstractTabOnly {
	private WebDriver driver;
	private String baseUrl;
	private StringBuffer verificationErrors = new StringBuffer();

	@Before
	public void setUp() throws Exception {
		driver = new FirefoxDriver();
		baseUrl = "http://europepmc.org/";
		driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
		System.out.println("Sleeping...");
		Thread.sleep(10000);
		System.out.println("Awake");
	}

	private void testUkpmcSearchImpl() throws Exception {
		driver.get(baseUrl + "/abstract/MED/11752295");
		for (int second = 0;; second++) {
			if (second >= 60)
				fail("timeout");
			try {
				if (isElementPresent(By
						.xpath("//html/body/div[3]/div/div[2]/div[1]/div/div/div[2]/div[1]/div[6]/div/table[2]/tbody/tr/td"))) {
					break;
				}
			} catch (Exception e) {
				System.out.println("Exception: " + e.getMessage());
			}
			Thread.sleep(1000);
		}

		try {
			assertTrue(driver
					.findElement(
							By.xpath("//html/body/div[3]/div/div[2]/div[1]/div/div/div[2]/div[1]/div[6]/div/table[2]/tbody/tr/td"))
					.getText()
					.matches("^The Gene Expression Omnibus[\\s\\S]*$"));
		} catch (Error e) {
			verificationErrors.append(e.toString());
		}
	}

	@Test
	public void testAbstractPageAllTabs() throws Exception {
		long startTime = System.currentTimeMillis();
		int rounds = 1;
		for (int i = 0; i < rounds; i++) {
			System.out.println("Starting: " + i);
			testUkpmcSearchImpl();
			System.out.println("End: " + i);
		}
		long endTime = System.currentTimeMillis();
		long duration = (endTime - startTime) / rounds;
		System.out.println();
		System.out.println(duration);
	}

	@After
	public void tearDown() throws Exception {
		driver.quit();
		String verificationErrorString = verificationErrors.toString();
		if (!"".equals(verificationErrorString)) {
			fail(verificationErrorString);
		}
	}

	private boolean isElementPresent(By by) {
		try {
			driver.findElement(by);
			return true;
		} catch (NoSuchElementException e) {
			return false;
		}
	}
}
